<?php

namespace App\Models;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Log\CompanyLog;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;

class Company extends Model
{
    use Notifiable;
    const OPERATE_PID = 1;
    const MODEL = 'company';


    use AdminTrait;
    protected $table = 'company';
    protected $guarded = [];
//    protected $dateFormat = 'U';
    protected $connection = 'mysql_official';

    public function companyType()
    {
        return $this->belongsTo(CompanyType::class ,'model','id');
    }

    public function adminRegion()
    {
        return $this->belongsTo(AdminRegion::class ,'base_address','id');
    }

    public function customer()
    {
        return $this->hasOne(CustomerWx::class,'id','cust_id');
    }

    public static function getListAll($model=0)
    {
        $list=self::where('model',$model)
            ->orderBy('created_at','desc')
            ->select(self::getFieldDetail())
            ->get();
        return $list;
    }


    public static function getWhere($data_where=[])
    {
        $where=[];
        if(!empty($data_where['model']))
        {
            $where[]=[DB::raw('model in ('.$data_where['model'].')'),1];
        }
        if(isset($data_where['company_name']))
        {
            $where[]=['company_name','like','%'.$data_where['company_name'].'%'];
        }
        if(isset($data_where['domain_name']))
        {
            $where[]=['domain_name','like','%'.$data_where['domain_name'].'%'];
        }
        if(isset($data_where['name']))
        {
            $where[]=['name','like','%'.$data_where['name'].'%'];
        }
        if(isset($data_where['mobile']))
        {
            $where[]=['mobile','like','%'.$data_where['mobile'].'%'];
        }
        if(isset($data_where['email']))
        {
            $where[]=['email','like','%'.$data_where['email'].'%'];
        }
        if(isset($data_where['county_id']))
        {
            $where[]=['base_address','=',$data_where['county_id']];
        }
        else if(isset($data_where['city_id']))
        {
            $ids_arr=AdminRegion::getCountyIdsByPid($data_where['city_id'],2);
            if(!empty($ids_arr))
            {
                $ids_arr=implode(',',$ids_arr);
                $where[]=[DB::raw('base_address in ('.$ids_arr.')'),1];
            }
         }
        else if(isset($data_where['province_id']))
        {
            $ids_arr=AdminRegion::getCountyIdsByPid($data_where['province_id']);
            if(!empty($ids_arr))
            {
                $ids_arr=implode(',',$ids_arr);
                $where[]=[DB::raw('base_address in ('.$ids_arr.')'),1];
            }
         }
        if(!empty($data_where['start_time']))
        {
            $start_time_arr=explode(',',$data_where['start_time']);
            if(count($start_time_arr)==2)
            {
                $time_1=$start_time_arr[0];
                $time_2=$start_time_arr[1];
                $where[]=['start_time','>=',$time_1];
                $where[]=['start_time','<=',$time_2+86400-1];
            }
        }
        if(!empty($data_where['end_time']))
        {
            $time_arr=explode(',',$data_where['end_time']);
            if(count($time_arr)==2)
            {
                $time_1=$time_arr[0];
                $time_2=$time_arr[1];
                $where[]=['end_time','>=',$time_1];
                $where[]=['end_time','<=',$time_2+86400-1];
            }
        }
        return $where;
    }

    public static function getList($data_where=[],$skip=0,$size=10)
    {
        if (!isset($data_where['used'])) $data_where['used'] = 0;
        $where=self::getWhere($data_where);
        $select = self::with(['companyType','adminRegion','customer'])->where($where);
        if ($data_where['used'] == 3) {
            $select = $select->where(function ($query) {
                $query->orWhere('status',0)->orWhere([['status','=',1],['end_time','<=',time()]]);
            })->where('audit',1);
        } elseif ($data_where['used'] == 2 || $data_where['used'] == 1) {
            $company_ids = Order::select('company_id')->where('created_at','>',Carbon::now()->subDays(7)->timestamp)->groupBy('company_id')->get()->pluck('company_id');
            if ($data_where['used'] == 1) {
                $select = $select->where('status',1)->where('end_time','>',time())->whereIn('id',$company_ids);
            } else {
                $select = $select->where('status',1)->where('end_time','>',time())->whereNotIn('id',$company_ids);
            }
        } elseif ($data_where['used'] == 4) {
            $select = $select->where('status',0)->where('audit',0);
        }
        $count = $select->count();
        $list = $select->skip($skip)->take($size)
            ->orderBy('created_at','desc')
            ->select(self::getFieldDetail())
            ->get();
        $list=self::listTransform($list);
        return ['list'=>$list,'count'=>$count];
    }

    public static function getCount($data_where=[])
    {
        $where=self::getWhere($data_where);
        $count=self::where($where)
            ->count();
        return $count;
    }

    public static function getDetail($id)
    {
        $info=self::with([
            'adminRegion',
        ])->where('id',$id)
            ->select(self::getFieldDetail())
            ->first();
        if($info)
        {
            //判断是否有客服
            //$haskf = CustomerServiceAgent::whereRaw("FIND_IN_SET('".$id."',company_ids)")->first();
            /*$haskf = [];
            if($haskf)
                $info->cust=[
                  'cust_id'=>$haskf->id,
                  'name'=>$haskf->name,
                ];
            else
                $info->cust=[];*/
            if ($info->cust_id) {
                $haskf = CustomerWx::find($info->cust_id);
                $info->cust=[
                    'cust_id'=>$haskf->id,
                    'name'=>$haskf->name,
                ];
            } else {
                $info->cust=[];
            }
            $time_now=time();
            $left_time=$info->end_time-$time_now;
            $left_time=$left_time<0?0:$left_time;
            $info->left_time=self::Sec2TimeStatic($left_time);
            $info->mername=$info->adminRegion->mername;
            $info->commission_rate=str_replace('‰','',$info->commission_rate);
            unset($info->adminRegion);
        }
        return $info;
    }


    public static function getFieldList()
    {
        return ['id','company_name','company_fullname','name','mobile','email','address','status','model'];
    }

    public static function getFieldDetail()
    {
        return ['id','company_name','company_fullname','name','mobile','email','start_time','end_time','address','status','model','domain_name','bind_dispatch','long_lati','base_address','commission_rate','remark','renewal_money','product_ids','cust_id','salesman','contract','voucher','audit'];
    }

    public static function listTransform($list)
    {
        $list=$list->transform(function ($i,$k)
        {
            $time_now=time();
            $left_time=$i->end_time-$time_now;
            if($i->status && $left_time<=0)
            {
                $data_up=[
                    'status'=>0,
                ];
//                self::where('id',$i->id)->update($data_up);
            }
            $left_time=$left_time<0?0:$left_time;
            $i->left_time=self::Sec2TimeStatic($left_time);
            $i->model_name=$i->companyType->name;
            $i->mername=$i->adminRegion->mername;
            $i->mername=substr($i->mername,7);
            $i->customer_name = '';
            if (!empty($i->customer)) {
                $i->customer_name = $i->customer->name;
            }
            unset($i->companyType);
            unset($i->adminRegion);
            unset($i->customer);
            return $i;
        });
        return $list;
    }

    public static function getListByName($data)
    {
        $select=self::where([]);
        if(!empty($data['company_name']))
        {
            $select=$select->where('company_name','like','%'.$data['company_name'].'%');
        }
        if(!empty($data['model']))
        {
            $select=$select->where('model',$data['model']);
        }
        if(isset($data['no_group']))
        {
            $select=$select->where('group_client_id',0);
        }
        $list=$select->select('id','company_name','model')->get();
        return $list;
    }

    public static function addLog($pre,$next,$type,$method='')
    {
        $info = AdminOperateModule::where('pid',self::OPERATE_PID)->where('type',$type)->where('model',self::MODEL)->when($method,function ($query)use ($method){
            $query->where('method',$method);
        })->first();
        if (!empty($info)){
            $adminLog = new CompanyLog($pre,$next,$info);
            $adminLog->addLog();
        }
    }
}
